package com.miaosha.ms_05.controller;

import com.miaosha.ms_05.prefix.MiaoshaUserKey;
import com.miaosha.ms_05.result.Result;
import com.miaosha.ms_05.service.MiaoshaUserService;
import com.miaosha.ms_05.util.UUIdUtil;
import com.miaosha.ms_05.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

/**
 * @Description //TODO
 * @Author Administrator
 * @DATE 2020/9/16 21:43
 **/
@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private MiaoshaUserService miaoshaUserService;

    @RequestMapping("/to_login")
    public String toLogin() {
        return "login";
    }

    @RequestMapping("/do_login")
    @ResponseBody
    public Result<String> doLogin(HttpServletResponse response, @Valid LoginVo loginVo) {
        String token = UUIdUtil.genUUID();
        miaoshaUserService.login(loginVo, token);
        addCookie(response, token);
        return Result.success(token);
    }

    public void addCookie(HttpServletResponse response, String token) {
        //加入客户端 Cookie
        Cookie cookie = new Cookie(MiaoshaUserService.COOKIE_NAME_TOKEN, token);
        cookie.setMaxAge(MiaoshaUserKey.USERKEY_TOKEN_NAME.getExpireTime() * 24 * 1000);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
